package enumandlambda;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author shkstart
 * 实现 Callable 新建线程
 * @create 2022-11-28-14:00
 */
public class ThreadDemo8 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        创建Callable实例
        MyCallable myCallable = new MyCallable();
//    用于接收Callable 结果的对象
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
//        创建新线程
        Thread thread = new Thread(futureTask);
//        启动线程
        thread.start();
//        接收新线程执行的结果
        int result = futureTask.get();
        System.out.println(Thread.currentThread().getName()+
                "--新线程返回的结果为："+result);
    }
}

//Callable<V>可以接受任何数据类型
class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        //生成随机数0-9
        int randomNum = new Random().nextInt(10);
        System.out.println(Thread.currentThread().getName() +
                "--随机数：" + randomNum);
        return randomNum;
    }
}
